package com.example.simplejdbcdemo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.stereotype.Repository;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * @description: jdbcTemplate数据库操作类
 * @author: lzp
 * @createTime: 2021-11-20 17:25
 **/
@Repository
@Slf4j
public class BatchFooDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    public void batchInsert() {
        jdbcTemplate.batchUpdate("INSERT INTO FOO(BAR) VALUES(?)",
                new BatchPreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement ps, int i) throws SQLException {
                        ps.setString(1, "batch-" + i);
                    }

                    @Override
                    public int getBatchSize() {
                        return 2;
                    }
                });

        // 另一种方式
        List<Foo> list = new ArrayList<>();
        list.add(Foo.builder().id(100L).bar("other-100").build());
        list.add(Foo.builder().id(101l).bar("other-101").build());
        namedParameterJdbcTemplate.batchUpdate(
                "INSERT INTO FOO (ID, BAR) VALUES(:id, :bar)",
                SqlParameterSourceUtils.createBatch(list));
    }

}
